// let that
// this指向实例化对象
class Tab {
  constructor(id) {
    // that = this
    this.main = document.querySelector(id)
    this.addBtn = this.main.querySelector('.tabadd')
    this.ul = this.main.querySelector('.fisrstnav ul')
    this.sectionsParent = this.main.querySelector('.tabscon')
    this.init()
  }

  updata() {
    this.lis = this.main.querySelectorAll('.fisrstnav li')
    this.sections = this.main.querySelectorAll('.tabscon section')
    this.delBtns = this.main.querySelectorAll('.fisrstnav li .iconfont')
    this.spans = this.main.querySelectorAll('.fisrstnav li span:first-child')
  }

  init() {
    this.updata()
    this.addBtn.onclick = this.addTabs.bind(this)
    this.lis.forEach((item, index) => {
      item.onclick = this.toggleTabs.bind(this, item, index)
    })
    this.delBtns.forEach((item, index) => {
      item.onclick = this.delTabs.bind(this, item, index)
    })
    this.spans.forEach(item => {
      item.ondblclick = this.editTabs
    })
    this.sections.forEach(item => {
      item.ondblclick = this.editTabs
    })
  }

  clearClass() {
    this.lis.forEach((item, index) => {
      item.className = ''
      this.sections[index].className = ''
    })
  }

  toggleTabs(li, index) {
    // console.log(this);
    this.clearClass()
    li.className = 'liactive'
    this.sections[index].className = 'conactive'
  }

  addTabs() {
    // console.log(this)
    // console.log(this.ul)
    this.clearClass()
    let li = ` 
    <li class="liactive">
        <span>新增测试li</span>
        <span class="iconfont icon-guanbi"></span>
    </li>`
    this.ul.insertAdjacentHTML('beforeend', li)
    let section = `
    <section class="conactive">测试${Math.random()}</section>
    `
    this.sectionsParent.insertAdjacentHTML('beforeend', section)
    this.init()
  }

  delTabs(delBtns, index, e) {
    e.stopPropagation()
    // console.log(this.parentNode)
    delBtns.parentNode.remove()
    this.sections[index].remove()
    this.init()
    if (this.main.querySelector('.liactive')) return
    // this.lis[index - 1] ? this.lis[index - 1].click() : ''
    // this.lis[index - 1] && this.lis[index - 1].click()
    if (index === 0) return this.lis[index]?.click()
    this.lis[index - 1]?.click()
  }

  editTabs() {
    window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty()
    let str = this.innerHTML
    // console.log(str)
    this.innerHTML = `<input type="text">`
    let input = this.children[0]
    input.value = str
    input.select()
    input.onblur = function () {
      this.parentNode.innerHTML = this.value
    }
    input.onkeyup = function (e) {
      if (e.keyCode === 13) {
        this.blur()
      }
    }
  }
}

new Tab('#tab')
